import React, { PureComponent } from 'react'
import { Form, Button, Input, Divider, Icon, Upload, message } from 'antd'
import PropTypes from 'prop-types'

import Style from './property.css'

class propertyForm extends PureComponent {
  constructor (props) {
    super(props)
    this.state = {
      image: []
    }
    this.onChange = this.onChange.bind(this)
    this.next = this.next.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.firstImageChange = this.firstImageChange.bind(this)
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  firstImageChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      message.error('上传失败')
      this.setState({
        loading: false
      })
      return
    }

    if (file.status === 'done') {
      this.setState({
        loading: false,
        coverImg: {
          imageUrl: file.response && file.response.data.imageUrl,
          width: file.response && file.response.data.width,
          height: file.response && file.response.data.height
        }
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  onChange ({ file, fileList, event }) {
    let imageList = []
    const { image } = this.state
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (file.status === 'done') {
      imageList.push({
        imageUrl: file.response && file.response.data.imageUrl,
        width: file.response && file.response.data.width,
        height: file.response && file.response.data.height
      })

      this.setState({
        loading: false,
        image: image.concat(imageList)
      })
    }
    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  next () {
    const { image, coverImg } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.imageList = image
        values.coverImg = coverImg
        if (!values.coverImg) {
          message.warning('请上传商品封面')
          return
        }
        if (values.imageList && values.imageList.length <= 0) {
          message.warning('请上传商品相册')
          return
        }
        this.props.selectOper({
          attributeInfo: values
        })
      }
    })
  }

  handleClose (index) {
    const { image } = this.state
    const imageCp = image.slice(0, image.length)
    imageCp.splice(index, 1)
    this.setState({
      image: imageCp
    })
  }

  componentDidMount () {
    const { attributeInfo = {} } = this.props
    if (attributeInfo.imageList) {
      this.setState({
        image: attributeInfo.imageList,
        coverImg: attributeInfo.coverImg
      })
    }
  }

  render () {
    const { attributeInfo = {} } = this.props
    const { image, loading, coverImg } = this.state
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }

    const uploadButton = (
      <div className={Style[`${coverImg ? '' : 'image-container'}`]}>
        {
          coverImg ? <div className={Style['image']} style={{ backgroundImage: `url(${coverImg.imageUrl})` }} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )

    const uploadListButton = (
      <div className={Style['image-container']}>
        <>
          <Icon type={loading ? 'loading' : 'plus'} />
          <div className={Style['ant-upload-text']}>Upload</div></>
      </div>
    )

    return (
      <div className={Style['property-container']}>
        <Form {...formItemLayout} onSubmit={this.handleSubmit}>
          <Form.Item label='商品属性' colon={false} style={{ fontSize: '16px' }} />
          <Form.Item label='创作年份'>
            {getFieldDecorator('year', {
              initialValue: attributeInfo.year,
              rules: [{ required: true, message: '请输入创作年份!' }]
            })(
              <Input placeholder='请输入创作年份' />
            )}
          </Form.Item>
          <Form.Item label='材料'>
            {getFieldDecorator('material', {
              initialValue: attributeInfo.material,
              rules: [{ required: true, message: '请输材料!' }]
            })(
              <Input placeholder='请输入材料' />
            )}
          </Form.Item>
          <Form.Item label='规格'>
            {getFieldDecorator('specInfo', {
              initialValue: attributeInfo.specInfo,
              rules: [{ required: true, message: '请输入规格!' }]
            })(
              <Input placeholder='请输入规格' />
            )}
          </Form.Item>
          <Form.Item label='适用'>
            {getFieldDecorator('fit', {
              initialValue: attributeInfo.fit
            })(
              <Input placeholder='请输入' />
            )}
          </Form.Item>
          <Divider />
          <Form.Item label='商品封面' colon={false} style={{ fontSize: '16px' }} />

          <Form.Item wrapperCol={{ span: 12, offset: 4 }}>
            <Upload
              action='/file/upload/1.0'
              name='file'
              beforeUpload={this.beforeUpload}
              onChange={this.firstImageChange}
              showUploadList={false}
              withCredentials
              headers={{
                token: localStorage.getItem('token') || ''
              }}
            >
              {uploadButton}
              <Button>
                <Icon type='upload' /> 选择上传图片
              </Button>
            </Upload>
          </Form.Item>

          <Form.Item label='商品相册' colon={false} style={{ fontSize: '16px' }} />

          <Form.Item wrapperCol={{ span: 12, offset: 4 }} >
            <div className={Style['image-list']}>
              {
                image && image.length > 0 ? image.map((item, index) => <div key={index} className={Style['image-container']}>
                  <Icon type='close-circle' className={Style['close']} onClick={() => this.handleClose(index)} />
                  <img className={Style['image']} src={item.imageUrl} />
                  {/* {
                    index === 0 && <div className={Style['des']}>商品封面图</div>
                  } */}
                </div>) : uploadListButton
              }
            </div>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 12, offset: 4 }} help='最多可以上传5张图片，封面图片限定尺寸900:600' style={{ marginTop: '-24px' }}>
            <Upload
              action='/file/upload/1.0'
              name='file'
              onChange={this.onChange}
              beforeUpload={this.beforeUpload}
              showUploadList={false}
              withCredentials
              multiple
              headers={{
                token: localStorage.getItem('token') || ''
              }}
            >
              <Button>
                <Icon type='cloud-upload' /> 选择上传图片
              </Button>
            </Upload>
          </Form.Item>

          <Form.Item wrapperCol={{ span: 12, offset: 9 }}>
            <Button type='primary' ghost onClick={this.props.writeInfo}>
              上一步，填写商品信息
            </Button>
            <Button type='primary' style={{ marginLeft: '20px' }} onClick={this.next}>
              {/* 下一步，选择运营关联 */}
              完成，提交商品
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
}

propertyForm.propTypes = {
  stepChange: PropTypes.func,
  form: PropTypes.any
}

const property = Form.create()(propertyForm)
export default property
